/**
 * 初始化区域管理详情对话框
 */
var SubAreaInfoDlg = {
    subAreaInfoData : {},
    validateFields: {
        name: {
            validators: {
                notEmpty: {
                    message: '区域名称不能为空'
                },
                stringLength: {  
                    max: 20,
                    message: '区域名称最大长度不能超过20'
                }
            }
        },
        'lacCi[]': {
            validators: {
                notEmpty: {
                    message: '基站小区不能为空'
                }
            }
        },
        warningValue: {
            validators: {
                notEmpty: {
                    message: '警戒值（人）不能为空'
                },
                regexp: {
                     regexp: /^[1-9]\d{0,17}$/,
                     message: '警戒值（人）只能输入0-18位整数'
                }
            }
        },
        saturationValue: {
            validators: {
                notEmpty: {
                    message: '饱和值（人）不能为空'
                },
                regexp: {
                     regexp: /^[1-9]\d{0,17}$/,
                     message: '饱和值（人）只能输入0-18位整数'
                }
            }
        },
        severeValue: {
            validators: {
                notEmpty: {
                    message: '严重值（人）不能为空'
                },
                regexp: {
                     regexp: /^[1-9]\d{0,17}$/,
                     message: '严重值（人）只能输入0-18位整数'
                }
            }
        }
    }
};

/**
 * 全局变量
 */
var map;//地图对象
var overlays = [];//区域对象集合
var markers = [];//点对象集合
var cells = [];//lacci集合

/**
 * 清除数据
 */
SubAreaInfoDlg.clearData = function() {
    this.subAreaInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
SubAreaInfoDlg.set = function(key, val) {
    this.subAreaInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
SubAreaInfoDlg.get = function(key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
SubAreaInfoDlg.close = function() {
    parent.layer.close(window.parent.SubArea.layerIndex);
}

/**
 * 收集数据
 */
SubAreaInfoDlg.collectData = function() {
    var lonLat = getLonLat();
    var lacCi = getLacCi();
    if(lonLat!=null&&lonLat!=""){
        $("#lonLat").val(lonLat);
    }
    $("#lacCi").val(lacCi);
    this.set('id').set('pid').set('name').set('lacCi').set('lonLat').set('warningValue').set('saturationValue').set('severeValue');
}

/**
 * 验证数据是否为空
 */
SubAreaInfoDlg.validate = function () {
    $('#subAreaInfoForm').data("bootstrapValidator").resetForm();
    $('#subAreaInfoForm').bootstrapValidator('validate');
    return $("#subAreaInfoForm").data('bootstrapValidator').isValid();
}

/**
 * 提交添加
 */
SubAreaInfoDlg.addSubmit = function() {

    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }
    if ($("#lacCi").val() == null || $("#lacCi").val() =="") {
        Feng.error("基站小区不能为空");
        return;
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/area/sub/add", function(data){
        Feng.success("添加成功!");
        window.parent.SubArea.table.refresh();
        SubAreaInfoDlg.close();
    },function(data){
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.subAreaInfoData);
    ajax.start();
}

/**
 * 提交修改
 */
SubAreaInfoDlg.editSubmit = function() {

    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }
    if ($("#lacCi").val() == null || $("#lacCi").val() =="") {
        Feng.error("基站小区不能为空");
        return;
    }

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/area/sub/update", function(data){
        Feng.success("修改成功!");
        window.parent.SubArea.table.refresh();
        SubAreaInfoDlg.close();
    },function(data){
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.subAreaInfoData);
    ajax.start();
}

//获取地图的样式
function getStyleJson(){
    var styleJson = [
        {
            "featureType": "land",
            "elementType": "geometry",
            "stylers": {
                "color": "#e7f7fc"
            }
        },
        {
            "featureType": "water",
            "elementType": "all",
            "stylers": {
                "color": "#96b5d6"
            }
        },
        {
            "featureType": "green",
            "elementType": "all",
            "stylers": {
                "color": "#b0d3dd"
            }
        },
        {
            "featureType": "highway",
            "elementType": "geometry.fill",
            "stylers": {
                "color": "#a6cfcf"
            }
        },
        {
            "featureType": "highway",
            "elementType": "geometry.stroke",
            "stylers": {
                "color": "#7dabb3"
            }
        },
        {
            "featureType": "arterial",
            "elementType": "geometry.fill",
            "stylers": {
                "color": "#e7f7fc"
            }
        },
        {
            "featureType": "arterial",
            "elementType": "geometry.stroke",
            "stylers": {
                "color": "#b0d5d4"
            }
        },
        {
            "featureType": "local",
            "elementType": "labels.text.fill",
            "stylers": {
                "color": "#7a959a"
            }
        },
        {
            "featureType": "local",
            "elementType": "labels.text.stroke",
            "stylers": {
                "color": "#d6e4e5"
            }
        },
        {
            "featureType": "arterial",
            "elementType": "labels.text.fill",
            "stylers": {
                "color": "#374a46"
            }
        },
        {
            "featureType": "highway",
            "elementType": "labels.text.fill",
            "stylers": {
                "color": "#374a46"
            }
        },
        {
            "featureType": "highway",
            "elementType": "labels.text.stroke",
            "stylers": {
                "color": "#e9eeed"
            }
        }
    ]
    return styleJson;
}

//获取绘图工具的属性
function getToolOptions(){
    var toolOptions = {
        anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
        offset: new BMap.Size(5, 5), //偏离值
        scale: 0.7, //工具栏缩放比例
        drawingModes: [
            BMAP_DRAWING_POLYGON
        ]
    }
    return toolOptions;
}

//获取绘图形状的属性
function getStyleOptions(){
    var styleOptions = {
        strokeColor:"red",    //边线颜色。
        fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 3,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
        fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' //边线的样式，solid或dashed。
    }
    return styleOptions;
}

//获取图片对象
function getIcon(){
    var icon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
        offset: new BMap.Size(10, 25),
        imageOffset: new BMap.Size(0, 0 - 12 * 25)
    });
    return icon;
}

//获取绘图对象
function getDrawingManager(){
    var drawingManager = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingToolOptions: getToolOptions(),
        polygonOptions: getStyleOptions() //多边形的样式
    }); 
    return drawingManager;
}

//设置地图属性
function setMapOptions(point,city,style){
    map.centerAndZoom(point, 13);
    map.setCurrentCity(city); 
    map.enableScrollWheelZoom(true);
    map.setMapStyle(style);
}

//获取区域经纬度
function getLonLat(){
    var lonLat="";
    for(i=0; i<overlays.length; i++){
        var overlay = overlays[i].getPath();
        for(j=0; j<overlay.length; j++){
            var grid =overlay[j];
            lonLat += grid.lng + "," + grid.lat;
            if(j+1 != overlay.length){
                lonLat += ";";
            }
        }
        if(i+1 != overlays.length){
            lonLat += "&";
        }
    }
    return lonLat;
}

//获取区域内小区lacci
function getLacCi(){
    var lacCi = "";
    var length = $("#cellList").find(":checkbox").length;
    $("#cellList").find(":checkbox").each(function(index,element){
        if ($(this).prop("checked")==true) {
            lacCi += cells[index];
            if(index + 1 != length){
                lacCi  += ";";
            }
        }
    });
    return lacCi;
}

//打点函数
function addMarker(point,isDrag,style){
    var marker;
    if(style != null){
        marker = new BMap.Marker(point,style);
    } else {
        marker = new BMap.Marker(point);
    }
    if(isDrag == true){
        marker.enableDragging();
        marker.addEventListener("dragend",function(){
           
        });
    }
    map.addOverlay(marker);
}

//清除地图
function clearAll() {
    for(var i = 0; i < overlays.length; i++){
        map.removeOverlay(overlays[i]);
    } 
    overlays=[];
    for(var i = 0; i < markers.length; i++){
        map.removeOverlay(markers[i]);
    } 
    markers=[];
    cells=[];
}

//区域展示
function addArea(lonLat){
    if(lonLat != null && lonLat != ""){
        var polygonArr = lonLat.split("&");        
        for(i=0;i<polygonArr.length;i++){
            var polygon = new BMap.Polygon();
            var points = [];
            var pointArr = polygonArr[i].split(";");
            for(j=0;j<pointArr.length;j++){
                 var lon = pointArr[j].split(",")[0];
                 var lat = pointArr[j].split(",")[1];
                 var point = new BMap.Point(lon,lat);
                 points.push(point);
            }
            polygon.setPath(points);
            map.addOverlay(polygon);
        }
    }
}

//增加基站多选框
function addCheckbox(n,name){
    var html = "";
    html = "<label class='i-checks' id='checkbox"+n+"' style='width:250px'>"
    html += "<input class='form-control' type='checkbox' name='lacCi[]'>";
    html += name+"</label>";
    if(n%2==1){
        html += "</br>";
    }
    $("#cellList").append(html);
    $("#cellList :checkbox").prop('checked',true); 
    var checkbox = "#checkbox"+n;
    $(checkbox).click(function(){
        if ($(this).find(":checkbox").prop("checked")==true) {
            map.removeOverlay(markers[n]);
        }else{
            map.addOverlay(markers[n]);                            
        }
    });
    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
    });
}

//基站展示
function addCell(value){
    var lon = parseFloat(value.lon)+0.01185;
    var lat = parseFloat(value.lat)+0.00328;
    var lac = value.lac;
    var ci = value.ci;
    var marker =  new BMap.Marker(new BMap.Point(lon,lat));
    map.addOverlay(marker);
    markers.push(marker);
    cells.push(lac+","+ci);
}

$(function() {
    map = new BMap.Map("allmap",{enableMapClick: false});
    var oldPoint = new BMap.Point( $("#lon").val(),$("#lat").val());
    setMapOptions(oldPoint,$("#city").val(),{styleJson:getStyleJson()});
    addMarker(oldPoint,false,{icon: getIcon()});   
    addArea($("#lonLat").val());
    var cellJson = $("#cellJson").val();
    if(cellJson != null && cellJson != ""){
        cellJson = cellJson.replace(/'/g, '"');
        cellJson = $.parseJSON(cellJson);
        $.each(cellJson, function (n, value) {
            addCell(value);
            addCheckbox(n,value.cellName); 
        });
    }
    var drawingManager = getDrawingManager();
    //添加鼠标绘制工具监听事件，用于获取绘制结果
    drawingManager.addEventListener('overlaycomplete', function(e){
        clearAll();
        overlays.push(e.overlay);
        var condition = {};
        condition["lonLat"] = getLonLat();
        condition["city"] = $("#city").val();
        var ajax = new $axSyn(Feng.ctxPath + "/area/sub/listCell", 
            function(data){
                layer.load(1, {shade: false});
            },
            function(data){
                $("#cellList").empty();
                $("#lacCi").val("");
                // $("#subAreaInfoForm").bootstrapValidator('removeField','lacCi[]'); 
                $.each(data, function (n, value) {
                    addCell(value);
                    addCheckbox(n,value.cellName);    
                });
                // $('#subAreaInfoForm').bootstrapValidator('addField','lacCi[]');
                // $('#subAreaInfoForm').bootstrapValidator('addField','lacCi[]',{
                //     validators: {
                //         notEmpty: {
                //             message: '基站小区不能为空'
                //         }
                //     }
                // });
                layer.closeAll("loading");
            },function(data){
                layer.msg("系统错误");
                layer.closeAll("loading");
            }
        );
        ajax.set(condition);
        ajax.start();
    });
    Feng.initValidator("subAreaInfoForm", SubAreaInfoDlg.validateFields);
});
